package com.lyz.moil.core.servlet;

import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 * User: xi
 * Date: 13-10-29
 * Time: AM12:11
 * To change this template use File | Settings | File Templates.
 */
@WebServlet(name = "ProgressServlet")
public class ProgressServlet extends HttpServlet {

    public static String PERCENT_NAME = "percentName";
    public static String REST = "reset";

    public static void setProgress(HttpServletRequest request, Object v) {
        Object o = request.getSession().getAttribute(PERCENT_NAME);
        if (o != null) {
            String percentName = o.toString();
            request.getSession().setAttribute(percentName, v);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String percentName = request.getParameter(PERCENT_NAME);
        Object value = 0;
        if (StringUtils.isNotBlank(percentName)) {
            value = request.getSession().getAttribute(percentName);
            if (value == null) {
                value = 0;
            }
        }
        PrintWriter out = response.getWriter();
        out.print(value);
        out.flush();
        out.close();

        Integer v = Integer.valueOf(value.toString());
        if (v >= 100 || v < 0) {
            request.getSession().removeAttribute(percentName);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String percentName = request.getParameter(PERCENT_NAME);
        String reset = request.getParameter(REST);
        request.getSession().setAttribute(PERCENT_NAME, percentName);
        if (StringUtils.isNotBlank(reset) && reset.equals("true")) {
            request.getSession().removeAttribute(percentName);
        }
    }
}
